package com.example.jpa.config;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManager;
import java.util.Map;

/**
 * 主库事务配置
 *
 * @author 86188
 */
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "masterManagerFactory",
        transactionManagerRef = "masterTransactionManager",
        basePackages = {"com.example.jpa.master"}//配置扫描注解组件所在包
)
public class DruidTransactionMasterConfig {

    @Autowired
    @Qualifier("masterDataSource")
    private javax.sql.DataSource masterDataSource;

    @Autowired
    JpaProperties jpaProperties;

    /**
     * 获取jpa配置信息
     */
    private Map<String, String> getVendorProperties() {
        return jpaProperties.getProperties();
    }

    @Bean(name = "masterManagerFactory")
    public LocalContainerEntityManagerFactoryBean masterManagerFactory(EntityManagerFactoryBuilder builder) {
        return builder.dataSource(masterDataSource).properties(getVendorProperties())
                //扫描实体类所在包,用于自动建表
                .packages("com.example.jpa.pojo")
                //持久化单元的名称,只有一个EntityManagerFactory的时候可以省略,多个不能省略
                .persistenceUnit("masterPersistenceUnit").build();
    }

    @Bean(name = "masterEntityManager")
    public EntityManager masterEntityManager(EntityManagerFactoryBuilder builder) {
        return masterManagerFactory(builder).getObject().createEntityManager();
    }

    @Bean(name = "masterTransactionManager")
    public PlatformTransactionManager masterTransactionManager(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(masterManagerFactory(builder).getObject());
    }

}
